package com.xuwang.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.xuwang.Common.Constast;
import com.xuwang.Util.*;
import com.xuwang.pojo.FileBean;
import com.xuwang.pojo.User;
import com.xuwang.service.impl.PublicInfoServiceImpl;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * (User)表控制层
 *
 * @author smallseven
 * @version 1.0
 * @since 2021-08-31 15:29:52
 */
@Controller
@RequestMapping("/publicInfoController")
@Api(value = "(User)管理", tags = "(User)管理接口API")
@ApiResponses({
        @ApiResponse(code = 400, message = "请求参数不完整或者错误"),
        @ApiResponse(code = 302, message = "临时重定向，被拦截器栏了"),
        @ApiResponse(code = 304, message = "缓存数据"),
        @ApiResponse(code = 404, message = "找不到页面"),
        @ApiResponse(code = 405, message = "请求方式不正确，比如后台接收是post，但前端请求的是get"),
        @ApiResponse(code = 406, message = "页面地址和接口名冲突"),
        @ApiResponse(code = 415, message = "请求格式不正确，前端可能没有把请求头修改为json，也可能前端请求的json对象没有转换为字符串"),
        @ApiResponse(code = 500, message = "后台服务逻辑错误")
})
public class PublicInfoController {
    /**
     * 服务对象
     */
    @Resource
    private PublicInfoServiceImpl publicInfoService;


    /**
     * 用户注册，完成表单信息
     *
     * @param user
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/register", produces = "application/json;charset=UTF-8")
    @ResponseBody
    @ApiOperation(value = "普通用户注册", notes = "添加相关信息进行添加", httpMethod = "POST", response = String.class)

    public String register(@RequestBody @ApiParam(name = "user",value = "用户实体对象",required = true) User user) throws IOException {
        TableResult<String> result;
        System.out.println(user.toString());
        result = publicInfoService.register(user);
        return WriteJson.getJson(result);
    }

    /***
     *  获取用户手机号是否为本人
     * @param phoneNum
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "普通用户手机验证码", notes = "发送短信验证验证码", httpMethod = "POST", response = String.class)
    @ApiImplicitParam(name = "phoneNum", value = "手机号", paramType = "query", dataType = "String", required = true)
    @RequestMapping(value = "/getValidCode", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getValidCode( String phoneNum) throws Exception {
        String json;
        sendValidCode send = new sendValidCode();
        int code = send.getMsg(phoneNum);
        publicInfoService.updateCode(phoneNum,code);
        TableResult<Integer> result = new TableResult<>(200, Constast.PHONE_CODE_SUCCESS, 1, code);
        json = WriteJson.getJson(result);
        return json;
    }

    /**
     * 上传用户头像
     *
     * @param fileBean
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/fileUpLoad", produces = "application/json;charset=UTF-8")
    @ResponseBody
    @ApiOperation(value = "上传用户图像", notes = "上传用户图像", httpMethod = "POST", response = String.class)
    public String fileUpload(@Validated FileBean fileBean,HttpServletRequest request) throws IOException {
        //保存结果信息
        TableResult<String> userList = null;
        //保存到本地项目
        String uploadPath =  request.getServletContext().getRealPath("") + File.separator +  "upload" + File.separator;
        MultipartFile multipartFile = fileBean.getFile();
        String fileName = multipartFile.getOriginalFilename();
        File newFile = new File(uploadPath + fileName);
        System.out.println("newFile=" + newFile);
        FileCopyUtils.copy(multipartFile.getBytes(), newFile);
        //存储图片路径
        return "../upload/" + fileName;
    }

    /**
     * 验证用户账号密码和手机号接受验证实现安全登录
     *
     * @param user
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/login", produces = "application/json;charset=UTF-8")
    @ResponseBody
    @ApiOperation(value = "用户登录", notes = "登录", httpMethod = "POST", response = String.class)
    public String login(@RequestBody @ApiParam(name = "user",value = "用户名和密码",required = true) User user, HttpServletResponse response) throws Exception {
        TableResult<HttpServletResponse> result;
        result = publicInfoService.login(user, response);
        return WriteJson.getResponse(result.getCount(),result.getData());
    }

    /**
     * 更新用户头像信息
     * @param request
     * @param fileBean
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updateUserImg", produces = "application/json;charset=UTF-8")
    @ResponseBody
    @ApiOperation(value = "上传图像", notes = "上传图像", httpMethod = "POST", response = String.class)
    public String updateUserImg(HttpServletRequest request, @Validated FileBean fileBean) throws Exception {
        //从请求头中获取token
        String token=request.getHeader("Authorization");

        String src = fileUpload(fileBean,request);
        TableResult<String> result ;
        result=publicInfoService.updateUserImg(src,token);
        return WriteJson.getJson(result);
    }

    /**
     * 更新用户信息
     * @param user
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updateUserInfo", produces = "application/json;charset=UTF-8")
    @ResponseBody
    @ApiOperation(value = "用户修改基本信息", notes = "用户修改基本信息", httpMethod = "POST", response = String.class)
    public String updateUserInfo(@RequestBody User user) throws Exception {
        TableResult<String> result ;
        result=publicInfoService.updateUserInfo(user);
        return WriteJson.getJson(result);
    }

    /**
     * 导入Excel表格可导入用户头像
     */
    @RequestMapping(value = "/insertManyUser", produces = "application/json;charset=UTF-8")
    @ResponseBody
    @ApiOperation(value = "导入Excel表格可导入用户头像", notes = "导入Excel表格可导入用户头像", httpMethod = "POST", response = String.class)
    public String insertManyUser(MultipartFile file,HttpServletRequest request) throws Exception {
        TableResult<String> result ;
        //上传到哪个文件夹
        String dir="excel";
        //上传的保存路径
        String path= ExcelImage.uploadExcel(file,dir,request);
        result=publicInfoService.insertManyUser(path,request);
        return WriteJson.getJson(result);
    }

    /**
     * 下载导入模板
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/downloadExcel", produces = "application/json;charset=UTF-8")
    @ResponseBody
    @ApiOperation(value = "下载导入模板", notes = "下载导入模板", httpMethod = "POST", response = String.class)
    public void downloadExcel(HttpServletResponse response) throws Exception {
        response.sendRedirect("/excel/template.xlsx");
    }

    /**
     * 批量删除用户
     */
    @RequestMapping(value = "/deleteManyUser", produces = "application/json;charset=UTF-8")
    @ResponseBody
    @ApiOperation(value = "批量删除用户", notes = "批量删除用户", httpMethod = "POST", response = String.class)
    public String deleteManyUser(Integer[] ids) throws JsonProcessingException {
        TableResult<String> result ;
        result=publicInfoService.deleteManyUser(ids);
        return WriteJson.getJson(result);
    }
}
